package fun.cyhgraph.controller.merchant;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import fun.cyhgraph.annotation.AuthCheck;
import fun.cyhgraph.common.ErrorCode;
import fun.cyhgraph.common.UserConstant;

import fun.cyhgraph.exception.BusinessException;
import fun.cyhgraph.exception.ThrowUtils;
import fun.cyhgraph.model.dto.CategoryDTO;
import fun.cyhgraph.model.dto.CategoryTypePageDTO;
import fun.cyhgraph.model.entity.Category;
import fun.cyhgraph.model.entity.User;
import fun.cyhgraph.result.PageResult;
import fun.cyhgraph.result.Result;
import fun.cyhgraph.service.CategoryService;
import fun.cyhgraph.service.MerchantInfoService;
import fun.cyhgraph.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/merchant/category")
@Tag(name = "分类管理")
@Slf4j
public class CategoryController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private UserService userService;
    @Resource
    private MerchantInfoService merchantInfoService;

    /**
     * 新增分类
     * @return
     */

    @AuthCheck(mustRole = UserConstant.ADMIN_OR_MERCHANT_ROLE)
    @Operation(summary = "新增分类")
    @PostMapping
    public Result addCategory(@RequestBody CategoryDTO categoryDTO , HttpServletRequest request){
        ThrowUtils.throwIf(categoryDTO.getName() == null , ErrorCode.PARAMS_ERROR);
        if (categoryDTO.getMerchantId() == null){
            User user = userService.getLoginUser(request);
            categoryService.addCategory(categoryDTO , user.getId());
        }else {
            Integer merchantId = categoryDTO.getMerchantId();
            //校验商户是否存在
            merchantInfoService.judgeMerchantInfo(merchantId);
            categoryService.addCategory(categoryDTO , merchantId);
        }

        return Result.success("新增成功");
    }

    /**
     * 分类条件分页查询
     * @param categoryTypePageDTO
     * @return
     */
    @Operation(summary = "分类条件分页查询")
    @AuthCheck(mustRole = UserConstant.ADMIN_OR_MERCHANT_ROLE)
    @PostMapping("/page")
    public Result<PageResult> getPageList(@RequestBody CategoryTypePageDTO categoryTypePageDTO , HttpServletRequest request){
        PageResult pageResult = categoryService.getPageList(categoryTypePageDTO , request);
        return Result.success(pageResult);
    }

    /**
     * 根据id查询指定分类
     * @param id
     * @return
     */
    @Operation(summary = "根据id查询指定分类")
    @AuthCheck(mustRole = UserConstant.ADMIN_OR_MERCHANT_ROLE)
    @GetMapping("/{id}")
    public Result<Category> getById(@PathVariable Integer id ,@RequestParam(required = false) Integer merchantId, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getId, id);
        if (merchantId != null){
            queryWrapper.eq(Category::getMerchantId , loginUser.getId());
        }
        Category category = categoryService.getOne(queryWrapper);
        return Result.success(category);
    }

    /**
     * 分类的起售/停售
     * @return
     */
    @Operation(summary = "分类的起售/停售")
    @PutMapping("/status/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_OR_MERCHANT_ROLE)
    public Result onOff(@PathVariable Integer id ,@RequestParam(required = false) Integer merchantId, HttpServletRequest request){
        if (merchantId == null){
            Integer loginUser = userService.getLoginUser(request).getId();
            categoryService.onOff(id , loginUser);
        }else {
            categoryService.onOff(id , merchantId);
        }

        return Result.success("ok");
    }

    /**
     * 更新分类信息
     * @param categoryDTO
     * @return
     */
    @Operation(summary = "更新分类信息")
    @AuthCheck(mustRole = UserConstant.ADMIN_OR_MERCHANT_ROLE)
    @PutMapping
    public Result udpate(@RequestBody CategoryDTO categoryDTO , HttpServletRequest request){
        //校验
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(categoryDTO.getId() == null , ErrorCode.PARAMS_ERROR);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getMerchantId , loginUser.getId());
        queryWrapper.eq(Category::getId , categoryDTO.getId());
        Category category = categoryService.getOne(queryWrapper);
        ThrowUtils.throwIf(category == null , ErrorCode.NOT_FOUND_ERROR);

        categoryService.udpate(categoryDTO);

        return Result.success("更新成功");
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "根据id删除分类")
    @AuthCheck(mustRole = UserConstant.ADMIN_OR_MERCHANT_ROLE)
    public Result delete(@PathVariable Integer id ,@RequestParam(required = false) Integer merchantId, HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null , ErrorCode.NOT_LOGIN_ERROR);
        //删除id 为 id 、merchantId为loginUser.getId()的分类
        // 执行删除操作
        if (merchantId != null){
            boolean b = categoryService.deleteCategory(id, merchantId);
            if (!b){
                return Result.error("删除失败");
            }

        }else {
            boolean b = categoryService.deleteCategory(id, loginUser.getId());
            if (!b){
                return Result.error("删除失败");
            }
        }

        return Result.success("删除成功");
    }
}
